/** 加 */
export const add = (arg1, arg2, ...others) => {
  const r1 = (arg1 || 0).toString().split('.')[1]?.length || 0
  const r2 = (arg2 || 0).toString().split('.')[1]?.length || 0
  const c = Math.abs(r1 - r2)
  const m = 10 ** Math.max(r1, r2)
  if (c > 0) {
    const cm = 10 ** c
    if (r1 > r2) {
      arg1 = Number((arg1 || 0).toString().replace('.', ''))
      arg2 = Number((arg2 || 0).toString().replace('.', '')) * cm
    } else {
      arg1 = Number((arg1 || 0).toString().replace('.', '')) * cm
      arg2 = Number((arg2 || 0).toString().replace('.', ''))
    }
  } else {
    arg1 = Number((arg1 || 0).toString().replace('.', ''))
    arg2 = Number((arg2 || 0).toString().replace('.', ''))
  }
  let res = (arg1 + arg2) / m
  if (others && others.length) {
    const nums = [...others]
    while (nums.length) {
      res = add(res, nums.shift())
    }
  }
  return res
}

/** 减 */
export const subtract = (arg1, arg2, ...others) => {
  const r1 = (arg1 || 0).toString().split('.')[1]?.length || 0
  const r2 = (arg2 || 0).toString().split('.')[1]?.length || 0
  const m = 10 ** Math.max(r1, r2)
  const n = r1 >= r2 ? r1 : r2
  let res = (((arg1 || 0) * m - (arg2 || 0) * m) / m).toFixed(n)
  if (others && others.length) {
    const nums = [...others]
    while (nums.length) {
      res = subtract(res, nums.shift())
    }
  }
  return Number(res)
}

/** 乘 */
export const multiply = (arg1, arg2, ...others) => {
  const s1 = (arg1 || 0).toString()
  const s2 = (arg2 || 0).toString()
  const m = add(0, s1.split('.')[1]?.length, s2.split('.')[1]?.length)
  let res = (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / 10 ** m
  if (others && others.length) {
    const nums = [...others]
    while (nums.length) {
      res = multiply(res, nums.shift())
    }
  }

  return res
}

/** 除 */
export const divide = (arg1, arg2, ...others) => {
  const t1 = arg1?.toString().split('.')[1]?.length || 0
  const t2 = arg2?.toString().split('.')[1]?.length || 0
  const r1 = Number((arg1 || 0).toString().replace('.', ''))
  const r2 = Number((arg2 || 1).toString().replace('.', ''))
  let res = multiply(r1 / r2, 10 ** (t2 - t1))
  if (others && others.length) {
    const nums = [...others]
    while (nums.length) {
      res = divide(res, nums.shift())
    }
  }
  return res
}
